package com.jyf.redis.common.config;

import com.jyf.redis.common.interceptor.AccessLimitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**webMVC的配置类
 * @author Mr.贾
 * @time 2020/11/9 20:03
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private AccessLimitInterceptor accessLimitInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(accessLimitInterceptor)
                .addPathPatterns("/api/**");
    }

    //跨域处理
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");//允许所有的源访问
        config.setAllowCredentials(true);//允许请求中带着cookie
        config.addAllowedMethod("*");//允许哪些http请求方式
        config.addAllowedHeader("*");//允许请求头中额外带着哪些请求头
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);//表示所有的资源都允许跨域访问
        return new CorsFilter(configSource);
    }
}
